package com.ljf.framework.util;

import java.io.*;

/**
 * 说明：各种路径获取工具类
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/12
 */
public class PathUtil {

    /**
     * 获取当前应用jar包所在路径
     *
     * @return
     */
    public static String getJarPath() {
        String path = PathUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        int begIndex = 0;
        int endIndex = 0;
        if (LjfUtils.isRunInIDEA()) {
            path = path.substring(1);
            endIndex = path.lastIndexOf("/");
        } else if (LjfUtils.isRunInLinux()) {
            begIndex = 5;
            endIndex = path.indexOf("!");
            path = path.substring(0, endIndex);
            endIndex = path.lastIndexOf("/");
        } else if (LjfUtils.isRunInWindows()) {
            begIndex = 6;
            endIndex = path.indexOf("!");
            path = path.substring(0, endIndex);
            endIndex = path.lastIndexOf("/");
        }

        path = path.substring(begIndex, endIndex)+"/";
        try {
            path = java.net.URLDecoder.decode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 获取resource下的文件
     *
     * @param fileName 文件名
     */
    public static void getResource(String fileName) {
        InputStream in = PathUtil.class.getClassLoader().getResourceAsStream(fileName);
        printFileContent(in);
    }

    public static void printFileContent(Object obj) {
        if (null == obj) {
            throw new RuntimeException("参数为空");
        }
        BufferedReader reader = null;
        try {
            // 如果是文件路径
            if (obj instanceof String) {
                reader = new BufferedReader(new FileReader(new File((String) obj)));
                // 如果是文件输入流
            } else if (obj instanceof InputStream) {
                reader = new BufferedReader(new InputStreamReader((InputStream) obj));
            }
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
